package com.k.kpp.util.rpc.netty.udp.server;

import com.k.kc.util.thread.ThreadUtils;
import com.k.kpp.util.rpc.netty.XMLUtils;
import com.k.kpp.util.rpc.netty.model.DataChangeProtocol;
import com.k.kpp.util.rpc.netty.model.XmlResult;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import javax.xml.bind.JAXBException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author k
 */
public class NettyUdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private volatile static BlockingQueue<NettyUdpResponseQueue> responseDataQueue = new LinkedBlockingQueue<>(1024);
    private static final String[] DICTIONARY = {"只要功夫深，铁棒磨成针。", "旧时王谢堂前燕，飞入寻常百姓家。",
            "洛阳亲友如相问，一片冰心在玉壶。", "一寸光阴一寸金，寸金难买寸光阴。", "老骥伏枥，志在千里。烈士暮年，壮心不已！"};

    private String nextQuote() {
        int quoteId = ThreadLocalRandom.current().nextInt(DICTIONARY.length);
        return DICTIONARY[quoteId];
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        InetSocketAddress from = msg.sender();
        String data = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println("Udp server channelRead0: thread:"+Thread.currentThread()+" from:"+from+" data:"+data);

//        String req = msg.content().toString(CharsetUtil.UTF_8);
//        XmlResult xmlResult = XMLUtils.xmlToObj(XmlResult.class,req,"utf-8");
//        String ack = DataChangeProtocol.getProtocolDataUpdateAck(xmlResult.getGuid());
//        ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(ack, CharsetUtil.UTF_8), msg.sender()));

        responseDataQueue.put(new NettyUdpResponseQueue(ctx,from,data));
        new Thread(new Runnable() {
            @Override
            public void run() {
                responseData();
            }
        }).start();
    }
    private static void responseData(){
        try {
            NettyUdpResponseQueue wrapper = responseDataQueue.take();
            ChannelHandlerContext ctx = wrapper.getChannelHandlerContext();
            String dataStr = wrapper.getData();
            System.out.println(String.format("responseData: tid:%s,wrapper:%s,datastr:%s",Thread.currentThread(),wrapper,dataStr));
            XmlResult xmlResult = XMLUtils.xmlToObj(XmlResult.class,dataStr,"utf-8");
            String ack = DataChangeProtocol.getProtocolDataUpdateAck(xmlResult.getGuid());
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(ack, CharsetUtil.UTF_8), wrapper.getFrom()));
        } catch (Exception e) {
            System.out.println(String.format("responseData error: tid:%s",Thread.currentThread()));
        }
    }
    private void sleep(long time, TimeUnit unit){
        try {
            System.out.println("睡眠："+unit.toMillis(time)+"毫秒");
            unit.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void messageReceived(){}

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // TODO Auto-generated method stub
        cause.printStackTrace();
        ctx.close();
        cause.printStackTrace();
    }
}